﻿using Microsoft.AspNet.SignalR;
using Sustainalytics.OAuth.Services.Common;
using Sustainalytics.Utils.Logging.Serilog.Messages;
using Sustainalytics.Utils.Serilog;
using System;
using System.Diagnostics;
using System.Threading.Tasks;

namespace Sustainalytics.Accounts.Service.SignalRHub
{
    public class UserLoginHub : Hub
    {
        private static readonly object locker = new object();

        private readonly UserLoginHubManager _manager;

        public UserLoginHub()
        {
            _manager = UserLoginHubManager.Instance;
        }

        private void ShowMsg(string msg)
        {
            Debug.WriteLine(msg);
            Console.WriteLine(msg);
        }

        public override Task OnConnected()
        {
            lock (locker)
            {
                ShowMsg("Connects");
                CommonEventSerilog.Log.Info(AuthServiceMessage.SignalRHubOnConnected, Context.User.Identity.Name, Context.ConnectionId);
                if (Context.User.Identity.IsAuthenticated)
                {
                    _manager.AddOrUpdateClients(Context.User.Identity.Name, Context.ConnectionId);
                }
                return base.OnConnected();
            }
        }

        public override Task OnDisconnected(bool stopCalled)
        {
            lock (locker)
            {
                CommonEventSerilog.Log.Info(AuthServiceMessage.SignalRHubOnDisconnected, Context.User.Identity.Name, Context.ConnectionId);
                ShowMsg("Disconnects");
                _manager.RemoveClients(Context.User.Identity.Name, Context.ConnectionId);
                return base.OnDisconnected(stopCalled);
            }
        }

        public override Task OnReconnected()
        {
            lock (locker)
            {
                ShowMsg("Reconnects");
                CommonEventSerilog.Log.Info(AuthServiceMessage.SignalRHubOnReconnected, Context.User.Identity.Name, Context.ConnectionId);
                if (Context.User.Identity.IsAuthenticated)
                {
                    _manager.AddOrUpdateClients(Context.User.Identity.Name, Context.ConnectionId);
                }
                return base.OnReconnected();
            }
        }
    }
}
